package com.zs;

import com.rabbitmq.client.*;

import java.io.*;
import java.util.concurrent.TimeoutException;

/**
 * Description:
 *
 * @author: zsq-1186
 * Date: 2017-08-18-10:56
 */
public class RecevieLogToFile {

    public static final String EXCHANGE_NAME="log";
    public static final String LOG_NAME="log.log";


    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPassword("guest");
        factory.setUsername("guest");

        Connection connection=factory.newConnection();
        Channel channel=connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME,"fanout");

        String queueName=channel.queueDeclare().getQueue();

        channel.queueBind(queueName,EXCHANGE_NAME,"");
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        Consumer consumer=new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println(" [x] Received '" + new String(body) + "' ready to file");
                writeToFile(body);
            }
        };
        channel.basicConsume(queueName, true, consumer);


    }

    public static void writeToFile(byte[] body) throws IOException {
        File logFile=new File(LOG_NAME);
        if(!logFile.exists()){
            logFile.createNewFile();
        }
        FileOutputStream outputStream=new FileOutputStream(logFile,true);
        BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(outputStream);
        bufferedOutputStream.write(body);
        outputStream.flush();
        bufferedOutputStream.flush();
        outputStream.close();
        bufferedOutputStream.close();
    }
}
